package plugin

import (
	"gitee.com/mkwchecking/k-scaffold/config"
	otlog "gitee.com/mkwchecking/k-scaffold/pkg/rely/log/otel"
	"gitee.com/mkwchecking/k-scaffold/pkg/rely/trace"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/propagation"
)

func (p *Plugins) GetTrace() (*trace.Trace, error) {
	if p._trace != nil {
		return p._trace, nil
	}

	log, err := p.GetLogger()
	if err != nil {
		return nil, err
	}

	traceConfig, err := config.GetTrace()
	if config.IsNotConfigured(err) {
		return nil, nil
	} else if err != nil {
		return nil, err
	}

	appConf := config.Get().App

	tracing, err := trace.New(
		p.Ctx(),
		trace.OTPLProtocol(traceConfig.Protocol),
		traceConfig.Endpoint,
		trace.WithServiceName(appConf.Name),
		trace.WithEnv(appConf.Env.String()),
		trace.WithErrorLogger(otlog.NewLogger(log.Logger)),
	)
	if err != nil {
		panic(err)
	}

	otel.SetTracerProvider(tracing.TracerProvider())
	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
		propagation.TraceContext{},
		propagation.Baggage{},
	))

	p._trace = tracing
	return p._trace, nil
}
